package com.fizzkai.p2p.website.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fizzkai.p2p.core.exception.DisplayableException;
import com.fizzkai.p2p.core.util.AjaxResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class AllExceptionHandler {
    private static final ObjectMapper mapper = new ObjectMapper();

    @ExceptionHandler
    public void handler(HandlerMethod hm, Exception ex, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // JSON 拦截
        if (hm.hasMethodAnnotation(ResponseBody.class)) {
            jsonHandler(hm, ex, req, resp);
            return;
        }
        // 普通拦截
//        req.getRequestDispatcher("error/500.ftl").forward(req, resp);
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("<pre>");
        ex.printStackTrace(resp.getWriter());
        resp.getWriter().write("</pre  >");
        ex.printStackTrace(System.out);
    }

    private void jsonHandler(HandlerMethod hm, Exception ex, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String value = null;
        resp.setContentType("application/json;charset=UTF-8");
        if (DisplayableException.class.isInstance(ex)) {
            value = mapper.writeValueAsString(new AjaxResult(ex.getMessage(), false));
        } else {
            value = mapper.writeValueAsString(new AjaxResult("系统出错，请联系管理人员！！", false));
            // 测试 用，打印 异常
            ex.printStackTrace();
        }
        resp.getWriter().write(value);

    }


//    @ExceptionHandler
//    public void handler(HandlerMethod hm, HttpServletResponse resp, Exception ex, HttpServletRequest req) throws Exception {
//        // JSON 请求
//        if (hm.hasMethodAnnotation(ResponseBody.class)) {
//            jsonHandler(ex, resp);
//            return;
//        }
//        req.getRequestDispatcher("/error/404.ftl").forward(req, resp);
//    }
//    private void jsonHandler (Exception ex, HttpServletResponse resp) throws Exception {
//        String value = new ObjectMapper().writeValueAsString(new AjaxResult(ex.getMessage(), false));
//        resp.setContentType("application/json;charset=UTF-8");
//        if (DisplayableException.class.isInstance(ex)) {
//            resp.getWriter().print(value);
//        } else {
//            // 打印到日志
//            ex.printStackTrace();
//            resp.getWriter().print("系统异常了，请联系管理员！！");
//        }
//    }
}
